package com.sap.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sap.common.utils.PageUtils;
import com.sap.common.utils.Query;
import com.sap.mall.product.dao.CategoryDao;
import com.sap.mall.product.entity.CategoryEntity;
import com.sap.mall.product.service.CategoryBrandRelationService;
import com.sap.mall.product.service.CategoryService;
import com.sap.mall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        // 2.组装父子分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> level = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(menu -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level;
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        // TODO: 2021/1/2 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }


    /**
     * 级联更新所有的数据
     * @CacheEvict:失效模式
     * 1、同时进行多种缓存操作，@Caching
     * 2、指定删除某个分区下的所有数据  @CacheEvict(value = "category", allEntries = true)
     * 3、存储同一类型的数据，都可以指定成同一个分区。
     * @param category
     * @CacheEvict 失效模式的使用
     */
//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category", key = "'getLevel1Categorys'")
//    })
    @CacheEvict(value = "category", key = "'getLevel1Categorys'")
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = {"category"}, key = "'getLevel1Categorys'",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Catogorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        /** 1、空结果缓存：解决缓存穿透
         *  2、设置过期时间（加随机值），解决缓存雪崩
         *  3、枷锁：解决缓存击穿
         */
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
            return catalogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> resutl = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return resutl;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        // 锁的名字，锁的粒度，越细越快
        // 锁的粒度；具体缓存的是某个数据，product-11-lock
        RLock lock = redisson.getLock("catalogJson-lock");

        Map<String, List<Catelog2Vo>> catalogJson;
        try {
            lock.lock();
            catalogJson = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return catalogJson;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        String value = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("catalogJson-lock", value, 30, TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Catelog2Vo>> catalogJson;
            try {
                catalogJson = getDataFromDb();
            } finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";

                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("catalogJson-lock"), value);
            }
            return catalogJson;
        } else {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }
    }

    public Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> resutl = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return resutl;
        }

        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 1、查出所有一级分类
        List<CategoryEntity> level1Catogorys = getParent_cid(selectList, 0L);
        // 2、封装数据

        Map<String, List<Catelog2Vo>> parent_cid = level1Catogorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1、每一个得一级分类，查到这个一级分类得二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 1、当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Colelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Colelog != null) {
                        List<Catelog2Vo.Calelog3Vo> collect = level3Colelog.stream().map(l3 -> {
                            Catelog2Vo.Calelog3Vo calelog3Vo = new Catelog2Vo.Calelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return calelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {


        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 1、查出所有一级分类
        List<CategoryEntity> level1Catogorys = getParent_cid(selectList, 0L);
        // 2、封装数据

        Map<String, List<Catelog2Vo>> parent_cid = level1Catogorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1、每一个得一级分类，查到这个一级分类得二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 1、当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Colelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Colelog != null) {
                        List<Catelog2Vo.Calelog3Vo> collect = level3Colelog.stream().map(l3 -> {
                            Catelog2Vo.Calelog3Vo calelog3Vo = new Catelog2Vo.Calelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return calelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid().equals(parent_cid)).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(entities -> {
            return entities.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}